package com.yy.micro.magic.core.loader.impl;

import com.yy.micro.magic.core.context.ResourceManager;
import com.yy.micro.magic.core.provider.impl.CodeMapResourceProvider;
import com.yy.micro.magic.ext.domain.code.CodeMapProvider;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.Resource;
 /**
   * @author YY
   * @version 1.0.0
   * @update 2021/9/22 9:20 下午
   * @description: 码表配置文件加载器，默认读取项目resources目录"magic-cube/code-map/"下的后缀为"*.json"文件。
  * 码表配置文件是原码表与目标码表的一一映射关系。原码表的value值必须唯一。如：
  * {
  *   "planCode": "test",
  *   "codeMaps": [
  *     {
  *       "name": "test",
  *       "items": [
  *         {
  *           "codeName": "test",
  *           "srcItemName": "SF",
  *           "srcValue": "F",
  *           "targetItemName": "SF2",
  *           "targetValue": "Fast"
  *         },
  *         {
  *           "codeName": "test",
  *           "srcItemName": "SN",
  *           "srcValue": "N",
  *           "targetItemName": "SN2",
  *           "targetValue": "North"
  *         }
  *       ]
  *     }
  *   ]
  * }
 */
@Component
public class CodeMapResourceLoader extends AbstractResourceLoader<CodeMapProvider>{


    @Value("${spring.micro.map.code_path:/magic-cube/code-map/}")
    private String codeBasePath;

    @Value("${spring.micro.map.code_postfix:*.json}")
    private String codePostfix;
    @Autowired
    private ResourceManager manager;

    @Resource(name = "codeImpl")
    private CodeMapResourceProvider codeMapResourceProvider;
    @Override
    protected void handle(final List<CodeMapProvider> resources) {
        if (!CollectionUtils.isEmpty(resources)){
            if (null != codeMapResourceProvider){
                resources.forEach(r->{
                    codeMapResourceProvider.regist(r.getPlanCode(),r.getCodeMaps().stream().collect(Collectors.toSet()));
                });
            }
        }
        super.handle(resources);
    }

    @Override
    protected String getResourcePost() {
        return codePostfix;
    }

    @Override
    protected String getResourcePath() {
        return codeBasePath;
    }

    @Override
    protected Class<CodeMapProvider> getResourceClass() {
        return CodeMapProvider.class;
    }
}
